package com.duoec.doc.mock.service;

import com.duoec.doc.mock.config.DocMockConfig;
import com.duoec.doc.mock.dto.DuoMockRequest;
import com.duoec.doc.mock.dto.DuoMockResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @author xuwenzhen
 * @date 2020/2/6
 */
@Service
public class MockSender {
    private static final Logger logger = LoggerFactory.getLogger(MockSender.class);
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    @Autowired
    private DocMockConfig docMockConfig;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private OkHttpClient okHttpClient;

    public DuoMockResponse mock(DuoMockRequest mockRequest) {
        String url = docMockConfig.getDocServer() + "/api/mock/rest";
        String requestBody;
        try {
            requestBody = objectMapper.writeValueAsString(mockRequest);
        } catch (JsonProcessingException e) {
            logger.error("系列化转发请求失败！", e);
            return DuoMockResponse.error("系列化转发请求失败");
        }
        Request mockOkRequest = new Request.Builder()
                .url(url)
                .addHeader("cache-control", "no-cache")
                .post(RequestBody.create(requestBody.getBytes(), JSON))
                .build();

        ResponseBody body;
        Response mockResponse;
        try {
            mockResponse = okHttpClient.newCall(mockOkRequest).execute();
            body = mockResponse.body();
        } catch (IOException e) {
            logger.error("调用duo-doc mock接口失败！url={}, req={}", url, requestBody, e);
            return DuoMockResponse.error("调用duo-doc mock接口失败");
        }

        if (body == null) {
            return DuoMockResponse.success();
        }
        try {
            String bodyStr = body.string();
            if (StringUtils.isEmpty(bodyStr)) {
                return DuoMockResponse.success();
            }
            return objectMapper.readValue(bodyStr.getBytes("UTF-8"), DuoMockResponse.class);
        } catch (IOException e) {
            logger.error("读取mock接口响应体失败！url={}, req={}", url, requestBody, e);
            return DuoMockResponse.error("读取mock接口响应体失败");
        }
    }
}
